package com.haoxuer.discover.site.rest.resource;

import com.haoxuer.discover.data.core.Finder;
import com.haoxuer.discover.data.page.Filter;
import com.haoxuer.discover.rest.base.RequestTokenObject;
import com.haoxuer.discover.rest.base.ResponseTokenObject;
import com.haoxuer.discover.site.api.AppHandler;
import com.haoxuer.discover.site.data.dao.AppDao;
import com.haoxuer.discover.site.data.dao.AppVersionDao;
import com.haoxuer.discover.site.data.entity.App;
import com.haoxuer.discover.site.data.entity.AppVersion;
import com.haoxuer.discover.site.domain.request.AppRequest;
import com.haoxuer.discover.site.domain.request.VersionRequest;
import com.haoxuer.discover.site.domain.response.AppVersionResponse;
import com.haoxuer.discover.site.rest.convert.AppVersionResponseConver;
import com.haoxuer.discover.user.service.UserTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional
public class AppResource implements AppHandler {

  @Autowired
  AppDao appDao;

  @Autowired
  AppVersionDao versionDao;

  @Autowired
  UserTokenService tokenService;

  @Override
  public ResponseTokenObject findToken(AppRequest request) {
    ResponseTokenObject result = new ResponseTokenObject();
    long num = appDao.count(Filter.eq("appKey", request.getAppKey()));
    if (num < 1) {
      result.setCode(-1);
      result.setMsg("该程序不存在");
      return result;
    }
    Finder finder = Finder.create();
    finder.append("from App a where a.appKey =:appKey and a.appSecret=:appSecret ");
    finder.setParam("appKey", request.getAppKey());
    finder.setParam("appSecret", request.getAppSecret());

    App app = appDao.findOne(finder);
    if (app == null) {
      result.setCode(-2);
      result.setMsg("密钥不正确");
      return result;
    }
    result.setToken(tokenService.token(app.getId()));
    return result;
  }

  @Override
  public ResponseTokenObject refreshToken(RequestTokenObject request) {
    ResponseTokenObject result = new ResponseTokenObject();
    try {
     Long id= tokenService.user(request.getToken());
      result.setToken(tokenService.token(id));
    } catch (Exception e) {
      result.setCode(-1);
      result.setMsg("token无效");
    }
    return result;
  }

  @Override
  public AppVersionResponse version(VersionRequest request) {
    AppVersionResponse result = new AppVersionResponse();
    if (request.getId() == null) {
      request.setId(1L);
    }
    App app = appDao.findById(request.getId());
    if (app == null) {
      result.setCode(-2);
      result.setMsg("app信息不存在");
      return result;
    }
    AppVersion version = versionDao.last(request.getId());
    if (version == null) {
      result.setCode(-2);
      result.setMsg("app版本信息不存在");
      return result;
    }
    result = new AppVersionResponseConver().conver(version);
    return result;
  }
}
